//
//  DKCore+HelperController.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "DKCore.h"
#import "OrderDetailViewController.h"

@implementation DKCore (HelperController)

- (void)loginController:(VoidBlock)finishBlock{
    
    LoginViewController *loginController = [[LoginViewController alloc]init];
    
    UINavigationController *naVController =[[UINavigationController alloc]initWithRootViewController:loginController];
    
    naVController.finishBlock = finishBlock;
    
    naVController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    
    [self.mainTabbarController presentViewController:naVController animated:YES completion:nil];
    
}


- (void)showTokenExpireAlert:(BOOL)isExpire{
    if (self.tokenExpireAlertView) {
        [self.tokenExpireAlertView removeFromSuperview];
    }
    
    self.tokenExpireAlertView = [[AlertTokenExpireView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:ASLocalizedString(@"ExpireTips") withSureStr:ASLocalizedString(@"OK")];
    
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    [window addSubview:self.tokenExpireAlertView];
}

- (void)showNetErrorAlertView{
    
    if (self.netErrorAlertView) {
        [self.netErrorAlertView removeFromSuperview];
    }
    NSString *titleStr = ASLocalizedString(@"ErrorNetTips");
    NSString *cancelBtnStr = ASLocalizedString(@"Stop");
    NSString *sureBtnStr = ASLocalizedString(@"Turning On");
    
    self.netErrorAlertView = [[AlertView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:titleStr withCancelStr:cancelBtnStr withSureStr:sureBtnStr];
    
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    [window addSubview:self.netErrorAlertView];
    
    self.netErrorAlertView.clickSureBlock = ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
                            
        }];
    };
}

- (void)jumpWLAlertView:(VoidBlock)block{
    if (self.wlAlertView) {
        [self.wlAlertView removeFromSuperview];
    }
    self.wlAlertView = [[AlertDCView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"" withDescStr:[NSString stringWithFormat:@"%@\n%@",ASLocalizedString(@"WlTips1"),ASLocalizedString(@"WlTips2")] withCancelStr:ASLocalizedString(@"Give Up") withSureStr:ASLocalizedString(@"Continue") withIsDC:NO];

    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    [window addSubview:self.wlAlertView];
    
    self.wlAlertView.clickCancelBlock = ^{
        if (block) {
            block();
        } 
    };
    
}

- (void)jumpToControllerWithUrlString:(NSString *)urlStr{
    if (PMStringIsEmpty(urlStr)) {
        return;
    }
    NSDictionary *dic = [urlStr getURLParameters];
    if ([esString(urlStr) containsString:kIsJumpAppOrderDetail]) {
        OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
        vc.idStr = esString(dic[@"largely"]);
        vc.hidesBottomBarWhenPushed = YES;
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
    }
    else if ([esString(urlStr) containsString:kIsJumpAppHome]){
        [[self currentViewController].navigationController popToRootViewControllerAnimated:NO];
        [self.mainTabbarController setSelectedIndex:0];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"1"}];
    }
    else if ([esString(urlStr) containsString:kIsJumpAppOrderList]){
        [[self currentViewController].navigationController popToRootViewControllerAnimated:NO];
        if ([CurrentUser mine].isYNLanguage) {
            [self.mainTabbarController setSelectedIndex:2];
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"3"}];
        } else {
            [self.mainTabbarController setSelectedIndex:1];
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"2"}];
        }
        
    }
    else if ([esString(urlStr) containsString:kIsJumpAppLogin]){
        [CurrentUser actionWhenLogin:^{
            
        }];
    }
    else {
        
        NSString *fh = @"?";
        if (!PMObjectIsEmpty(dic)) {
            fh = @"&";
        }
        
        
        urlStr = [urlStr stringByAppendingFormat:@"%@mauser=%@&rifles=%@&revolvers=%@&bring=%@&packing=%@&similes=%@&rumoured=%@&seaward=%@",fh,@"ios",kAppVersion,esString([[UIDevice currentDevice] name]),esString([IDFVTools getIDFV]),esString([UIDevice currentDevice].systemVersion),@"appstore-ca",esString([IDFVTools getIDFV]),esString([[NSUserDefaults standardUserDefaults] objectForKey:kCurrentLanguageCode])];
       
        if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
            urlStr = [urlStr stringByAppendingFormat:@"&emanation=%@",esString([CurrentUser mine].sessionKey)];
        }
        
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

        //resolve if url contains '#'
        NSString *realUrlStr = urlStr;
        NSString *lastPathComponent = urlStr.lastPathComponent;
        NSRange queryRange = [lastPathComponent rangeOfString:@"?"];//
        if (queryRange.location != NSNotFound && queryRange.length > 0) {
            
            NSString *queryOrignal = [lastPathComponent substringWithRange:NSMakeRange(queryRange.location+1,lastPathComponent.length -queryRange.location-1)];
               
            NSString *queryEncode = [queryOrignal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            NSString *lastPathComponentEncode = [lastPathComponent stringByReplacingOccurrencesOfString:queryOrignal withString:queryEncode];
            
            realUrlStr = [urlStr.stringByDeletingLastPathComponent stringByAppendingPathComponent:lastPathComponentEncode];
            
        }
        urlStr = realUrlStr;
       
        
        BaseWebViewController *vc = [[BaseWebViewController alloc] init];
        vc.urlStr = esString(urlStr);
        vc.hidesBottomBarWhenPushed = YES;
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark ---------initLocation------
- (void)initLocation{
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *newlocation = locations[0];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:newlocation completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
        
        if (!error) {
                        
            self.longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
            self.latitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            NSString *address = [NSString stringWithFormat:@"%@, %@, %@, %@, %@",placemark.ISOcountryCode,placemark.country,placemark.locality,placemark.subLocality,placemark.thoroughfare];
            self.ISOcountryCodeStr = esString(placemark.ISOcountryCode);
            self.countryStr = esString(placemark.country);
            self.localityStr = esString(placemark.locality);
            self.subLocalityStr = esString(placemark.subLocality);
            self.thoroughfareStr = esString(placemark.thoroughfare);
        
            if (self.isNeedUploadLocation) {
                [DataCategoryUpload uploadDataLocation];
            }
            
            
        }
       
    }];
    
    [self.locationManager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

@end



